# -*- coding: utf-8 -*-
# בש״ד
#
# Miraflores Blog for Django - Part of the Cuba Libre Project
# Copyright (C) 2009, Joshua "jag" Ginsberg <jag@flowtheory.net>
# 
# Por mi amor, que inspira a mi cada respiración y que echa de Cuba
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import datetime
from django.db import models
from django.db.models import Q
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth import models as auth
from django.core.urlresolvers import reverse
from django.contrib.sites import models as sites
from django.contrib.comments.moderation import moderator
from django.conf import settings
from tagging.models import Tag
from miraflores import akismetlib

class Category(models.Model):
    slug = models.SlugField(_(u'URL stub'), unique=True)
    name = models.CharField(_(u'Category name'), max_length=50)
    parent = models.ForeignKey('self', null=True, blank=True)
    icon_height = models.PositiveIntegerField(null=True, editable=False)
    icon_width = models.PositiveIntegerField(null=True, editable=False)
    icon = models.ImageField(upload_to='staticlib', height_field='icon_height',
                             width_field='icon_width', blank=True, null=True)
    
    def __unicode__(self):
        if not self.parent:
            return self.name
        else:
            return unicode(self.parent) + u'::' + self.name
    
    class Meta:
        verbose_name_plural = u'categories'

class BlogEntryManager(models.Manager):
    def get_query_set(self):
        return super(BlogEntryManager, self).get_query_set().filter(
            sites__id=settings.SITE_ID)
    
    def can_be_seen_by_user(self, user_obj):
        qs = self.get_query_set()
        if user_obj.is_staff:
            return qs
        qs = qs.exclude(published=False)
        if user_obj.is_anonymous():
            qs = qs.filter(limit_access=False)
        else:
            qs = qs.filter(Q(limit_access=False) | \
                           Q(permitted_users__id=user_obj.id) | \
                           Q(permitted_groups__user__id=user_obj.id))
        return qs.distinct()

class BlogEntry(models.Model):
    title = models.CharField(_(u'Title'),
                             max_length=200)
    body = models.TextField(_(u'Body'),
                            help_text=_((u'Use Markdown syntax. '
                                         u'Include &lt;!-- break --&gt; in the '
                                         u'body to require a reader to click '
                                         u'through to read the rest of the '
                                         u'entry.')))
    slug = models.SlugField(_(u'URL stub'))
    author = models.ForeignKey(auth.User, verbose_name=_(u'Author'),
                               related_name='author',
                               limit_choices_to={'is_staff': True})
    published = models.BooleanField(_(u'Published?'), default=False)
    last_updated = models.DateTimeField(_(u'Last updated'),
                                        default=datetime.datetime.now)
    limit_access = models.BooleanField(_(u'Limit access?'),
                                         default=False)
    permitted_users = models.ManyToManyField(
        auth.User,
        blank=True,
        verbose_name=_(u'Limit access to users'),
        related_name='permitted')
    permitted_groups = models.ManyToManyField(
        auth.Group,
        blank=True,
        verbose_name=_(u'Limit access to groups'))
    sites = models.ManyToManyField(sites.Site)
    categories = models.ManyToManyField(Category, null=True, blank=True)
    
    objects = BlogEntryManager()
    on_site = objects
    
    def _get_tags(self):
        return Tag.objects.get_for_object(self)

    def _set_tags(self, tag_list):
        Tag.objects.update_tags(self, tag_list)

    tags = property(_get_tags, _set_tags)
    
    def get_absolute_url(self):
        return reverse('miraflores_blog_entry_detail',
                       args=[self.last_updated.year,
                             '%.2d' % self.last_updated.month,
                             '%.2d' % self.last_updated.day,
                             self.slug])
    
    def __unicode__(self):
        return self.title
    
    class Meta:
        ordering = ['-last_updated']
        verbose_name_plural = u'Blog entries'
        
moderator.register(BlogEntry, akismetlib.AkismetModerator)

class BlogEntryUpdate(models.Model):
    blog_entry = models.ForeignKey(BlogEntry)
    body = models.TextField(_(u'Body'))
    author = models.ForeignKey(auth.User, verbose_name=_(u'Author'),
                               limit_choices_to={'is_staff': True})
    published = models.BooleanField(_(u'Published?'), default=False)
    last_updated= models.DateTimeField(_(u'Last updated'),
                                       auto_now=True)

    def __unicode__(self):
        return _(u'Update for %s') % self.blog_entry.title

    class Meta:
        ordering = ['-last_updated']
